package com.feiyisuo.sso.config;

import com.feiyisuo.sso.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Slf4j
public class OAuth2AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("sessionId:{}",request.getSession().getId());
        try {
            OAuth2Error error = ((OAuth2AuthenticationException) exception).getError();
            log.info("验证错误:{}",exception.getMessage());
        } catch (Exception e) {
            log.error("验证error:{}",exception);
        }
        WebUtils.renderString(
                response,
                "fail",
                401
        );
    }
}
